package com.online.jta.util.db;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 数据源通知
 * 
 * @author tongyufu
 *
 */
@Component
@Aspect
public class DataSourceAspectAdvice implements Ordered {

    @Pointcut("execution(* com.online.jta.dao..*.*(..))")
    public void point() {
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Before("point()")
    public void before(JoinPoint joinpoint) {
        //默认使用MySql数据源
        RoutingDataSource.setDataSourceKey(RoutingDataSource.MYSQL);
        Class[] interfaces = joinpoint.getTarget().getClass().getInterfaces();
        for (Class clz : interfaces) {
            if (clz.isInterface()) {
                for (Class clz2 : clz.getInterfaces()) {
                    if (clz2.isAssignableFrom(OracleDao.class)) {
                        RoutingDataSource.setDataSourceKey(RoutingDataSource.ORACLE);
                        break;
                    }
                }
            }
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    //@Around("point()")
    public Object around(ProceedingJoinPoint joinpoint) throws Throwable {
        Class[] interfaces = joinpoint.getTarget().getClass().getInterfaces();
        for (Class clz : interfaces) {
            if (clz.isInterface()) {
                for (Class clz2 : clz.getInterfaces()) {
                    if (clz2.isAssignableFrom(OracleDao.class)) {
                        RoutingDataSource.setDataSourceKey(RoutingDataSource.ORACLE);
                    }
                }
            }
        }
        Object response = joinpoint.proceed();
        //默认切回MySql数据源
        RoutingDataSource.setDataSourceKey(RoutingDataSource.MYSQL);
        return response;
    }

    @Override
    public int getOrder() {
        return 1;
    }

}
